const BodyParser = require('body-parser')
const jwt = require('jsonwebtoken')
const Mock = require('mockjs')

const userList = [
    {
        username: 'admin',
        password: '123',
        name: '张三',
        id: '1'
    },
    {
        username: 'user',
        password: '123',
        name: '李四',
        id: '2'
    }
]

const dataList = Mock.mock({
    "list|6": [
        {
            title: '@ctitle(3,4)',
            color: "@color",
            id: "@id",
            "list|100-500": [
                {
                    title: "@ctitle(3,6)",
                    date: "@date(yyyy-MM-dd)",
                    word: "@cword(5,10)",
                    id: "@id"
                }
            ]
        }
    ]
})

module.exports = app => {
    app.use(BodyParser.json())

    // 登录
    app.post('/api/login', (req, res) => {
        const { username, password } = req.body;

        const info = userList.find(item => item.password === password && item.username === username)

        if(info) {
            res.send({
                code: 1,
                msg: '登录成功',
                token: jwt.sign(info.id, '2208A')
            })
        } else {
            res.status(403)
            res.send({
                code: 0,
                msg: '登录失败，用户名或者密码错误'
            })
        }
    })

    // 获取用户信息
    app.get('/api/getUserInfo', (req, res) => {
        const { authorization } = req.headers;

        try {
            const id = jwt.verify(authorization, '2208A');

            const info = userList.find(item => item.id === id)

            res.send({
                code: 1,
                data: info
            })
        } catch (error) {
            res.status(402)

            res.send({
                code: 0,
                msg: '登录已过期，请重新登录'
            })
        }
    })

    // 首页列表接口
    app.post('/api/getList', (req, res) => {
        res.send({
            code: 1,
            data: dataList.list.map(item => {
                return {
                    title: item.title,
                    id: item.id,
                    color: item.color,
                    num: item.list.length
                }
            })
        })
    })

}